<template>
  <div class="top" id="chartRef"></div>
  <div class="legendbox">
    <ul>
      <li v-for="(item, i) in colorList.color">
        <span :style="{ backgroundColor: item }">
        </span>
        {{ colorList.data[i].name }}
      </li>
    </ul>
  </div>
  <div class="device_status_normal">
    <div class="statusTop" :class='"lang" + locale'>
      <span class="label">{{ t("lang.deviceStatus") }}： <span style="color: #C42125"
          v-if='props.errDev.length && value2'>
          {{ t("lang.abnormal") }}
        </span>
        <span class="normal" v-else> {{ t("lang.normal") }}</span></span>
      <el-switch style="--el-switch-on-color: #19fa77; --el-color-primary:#cad0db; --el-text-color-primary:#cad0db"
        v-model="value2" class="ml-2 switch" @change="overhaul" size="large"
        :inactive-text="t('lang.MessageScrolling')" />
    </div>
    <div>
      <div class="warnTextBox" v-if="value2">
        <vue3-seamless-scroll hover-stop="true" hover="true" v-model="scrollM" :list="props.errDev" :step="0.15">
          <div class="warnText" v-for="(item, index) in props.errDev" :key="index"
            style="padding:5px 0px; font-size: 14px">
            {{ item.nick_name }}&nbsp;&nbsp;<span style="color:#C42125">
              {{ item.macaddress }}
            </span>&nbsp;&nbsp;
            {{ locale == 'zh' ? '有故障风险' : "Risk of malfunction" }}!!!
          </div>
        </vue3-seamless-scroll>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
import { GetDeviceInfo, ProjectData, report } from '../utils/util';
import * as echarts from "echarts";
import { ref } from 'vue';
let value2 = new ref(false)
let scrollM = new ref(false)
let props = defineProps({
  partition: {
    type: Array,
    default: []
  },
  fid: {
    type: String,
    default: '-1'
  },
  bigPieFn: {
    type: Array,
    default: []
  },
  errDev: {
    type: Number,
    default: 1
  },
  switch: {
    type: Boolean,
    default: false
  }
})
let timer = null;
watch(
  () => props,
  (newVal, oldVal) => {
    console.log("fid", props.fid);
    console.log("errDev", props.errDev);
    console.log("bigPieFn", props.bigPieFn);
    console.log("switch", props.switch);
    // debugger
    if (timer != null) {
      clearInterval(timer)
    }
    let myChart = echarts.getInstanceByDom(document.getElementById("chartRef"));
    if (!myChart) // 如果不存在则创建
    {
      myChart = echarts.init(document.getElementById("chartRef"));
    }
    let params = new FormData();
    params.append('fid', props.fid);

    let wattHourMeter = '';
    $axios.post('/wattHourMeter/data', params).then(res => {
      wattHourMeter = res.data.data;
      /// proxy.$mitt.on('bigPieFn', (res) => {
      bigPie.value = bigPieFn.value;
      clearInterval(timer)
      echartsInitBigPie(myChart, bigPie.value, wattHourMeter)
      //  })

    }).catch(err => { })

    // getOnLineDev(props.fid)

  },
  {
    deep: true
  }
)
const { bigPieFn } = toRefs(props)
let colorList = ref({});
let onlineDev = ref([]);
const getOnLineDev = (id) => { // 
  let params = new FormData();
  params.append('fid', id);
  $axios.post('/operationDevice/getOnLineDev2', params).then(res => {
    onlineDev.value = new ProjectData(res.data.data, id).getOnlineDev();
    // option.series[0].data = data.onlineDev;
    // var myChart = echarts.init(document.getElementById('chart-view'));
    // myChart.setOption(option);
  }).catch(err => { })
  ///data.loading = false;
}

let dataIdx = 0;
const fondColor = (partition) => { // 白红交替，颜色自定义，如果只要2种颜色可以删除替换掉红色或者白色
  ////console.log("111", partition);
  let color = [
    '#FFC312', '#C4E538', '#F79F1F',
    '#1289A7', '#D980FA', '#B53471',
    '#EE5A24', '#0652DD', '#9980FA',
    '#EA2027', '#1B1464', '#5758BB'
  ]
  let len = partition.length;
  let colorArr = []
  for (let j = 0; j < len; j++) {
    if (j > color.length - 1) {
      j = 0;
      len -= color.length
    }
    colorArr.push(color[j])
  }
  for (let i = 0; i < partition.length; i++) {

    if ((partition[i].value1 - partition[i].sum != 0) && props.switch) {
      if (dataIdx === 1) {
        colorArr[i] = '#ffffff'
      } else if (dataIdx === 2) {
        colorArr[i] = '#cc0000'
      }
    }
  }
  switch (dataIdx) {
    case 0:
      dataIdx = 1;
      break;
    case 1:
      dataIdx = 2;
      break;
    default:
      dataIdx = 0
  }
  return colorArr;
}
let partitionN = [];
const echartsInitBigPie = (myChart, partition, wattHourMeter) => {
  window.clearInterval(timer);
  // console.log("饼图数据", partition);
  partitionN = JSON.parse(JSON.stringify(partition));
  for (let i = 0; i < partitionN.length; i++) {
    partitionN[i].value1 = partitionN[i].online;
    partitionN[i].value = partitionN[i].sum;
  }
  let top = '25%'
  let text = {
    text: t('lang.smartPartition'),
    left: 'center',
    top: top,
    textStyle: {
      fontSize: 16,
      textAlign: 'center',
      width: 30,
      height: 25,
      color: '#fff',
      // fontWeight: '900'
    }
  }
  myChart.on('mouseover', function (params) {
    const { name, value, offline, sum, value1 } = params.data;
    text.text = value1 != sum ? t('lang.abnormal') : t('lang.normal')
    let r = wattHourMeter.filter((i) => {
      return i.fid == params.data.id
    })
    // text.text = (params.data.power / 1000).toFixed(3) + " kwh"
    if (r.length) {
      let power = 0
      r.map((i) => power += i.power)
      text.text = power + " kwh"
      text.textStyle.fontSize = 12
    }
    ///showChart(params.data.bad_flag > 0 ? '异常' : "正常");

    // let sum = 0;
    // onlineDev.value.map((item) => {
    //   sum += item.value * 1
    // })
    myChart.setOption({
      title: {
        text: value1 != sum ? t('lang.abnormal') : t('lang.normal'),
        subtext: value1 + "/" + sum,
        left: 'center',
        top: top,
        textStyle: {
          fontSize: 16,
          textAlign: 'center',
          width: 30,
          height: 25,
          color: '#fff',
          fontWeight: '900'
        },
        subtextStyle: {
          fontFamily: "微软雅黑",
          fontSize: 16,
          color: '#fff',
        }
      },
    })
  });
  myChart.on('mouseout', function (params) {
    text.text = t('lang.smartPartition')
    text.textStyle.fontSize = 16
    myChart.setOption({
      title: {
        text: params.data.bad_flag > 0 ? t('lang.abnormal') : t('lang.normal'),
        subtext: '',
        left: 'center',
        top: top,
        textStyle: {
          fontSize: 16,
          textAlign: 'center',
          width: 30,
          height: 25,
          color: '#fff',
          fontWeight: '900'
        },
        subtextStyle: {
          fontFamily: "微软雅黑",
          fontSize: 16,
          color: '#fff',
        }
      },
    })
    showChart(t('lang.smartPartition'));
  });

  timer = setInterval(() => {
    colorList.value = { color: fondColor(partitionN), data: partitionN };
    // if (props.errDev == 0) {
    //   clearInterval(timer)
    // }
    //  ////console.log("数据",partitionN);
    myChart.setOption({
      title: text,
      animation: false,
      tooltip: {
        trigger: 'item',
        position: function (point, params, dom, rect, size) {
          // 外层div的大小
          let viewWidth = size.viewSize[0];
          let viewHeight = size.viewSize[1];

          // 提示框大小
          let boxWidth = size.contentSize[0];
          let boxHeight = size.contentSize[1];

          // 计算中心点坐标
          let x = (viewWidth - boxWidth) / 2;
          let y = (viewHeight - boxHeight) / 1.4;

          return [x, y];
        },
        formatter: function (data) {
          let arr = list.value.filter((item) => {
            return data.data.fid == item.id
          })
          return (arr[0].productName + "<br/>" + data.marker + data['name']
          )
        },
      },
      legend: {
        top: 'bottom',
        show: false,
        left: '26',
        itemWidth: 10, // 图例标记的图形宽度
        itemHeight: 10,
        icon: "circle",
        itemGap: 20,
        textStyle: {
          color: '#fff',
          fontSize: '14'
        },
        // pageIconColor: '#6495ed', //翻页下一页的三角按钮颜色
        // pageIconInactiveColor: '#aaa', //翻页（即翻页到头时）
        // pageIconSize: 18, //翻页按钮大小
        //  pageFormatter: ' ',//隐藏翻页的数字
        // pageButtonItemGap: -10,//翻页按钮的两个之间的间距
        padding: [
          90,  // 上
          10, // 右
          40,  // 下
          0, // 左
        ]
      },
      graphic: {
        type: "text",
        left: "center",
        top: "50%",
        style: {
          text: "",
          textAlign: "center",
          fill: "#fff",
          fontSize: 20,
        }
      },
      series: [
        {
          color: fondColor(partitionN),
          name: 'Access From',
          type: 'pie',
          center: ["50%", "27%"],
          radius: ['35%', '50%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          labelLine: {
            show: false
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          data: partitionN
        }
      ]
    });
  }, 200)
}
function showChart (text) {
  let map = echarts.init(document.getElementById('chartRef'));
  let option = map.getOption() // 获取option数据
  ////console.log("参数", option);
  option.title[0].text = text;
  /// option.series[0].data = [1, 2, 3] // 找到data修改数据
  map.setOption(option, true) // 重新渲染
}
let myChart = {};
let bigPie = ref([]);
let { proxy } = getCurrentInstance()
//

let list = ref([]);
const getuserDeviceCount = () => {
  $axios.post('/device/userDeviceCount', {}).then(res => {
    list.value = res.data.data;



  }).catch(err => { })
}

onMounted(() => {
  getuserDeviceCount();
  //   //const { wattHourMeter } = useModel('projectData');
  //   if (timer != null) {
  //     clearInterval(timer)
  //   }
  //   // let myChart = echarts.getInstanceByDom(chartRef.current);
  //   // if (!myChart) // 如果不存在则创建
  //   // {
  //   myChart = echarts.init(document.getElementById("chartRef"));
  //   //}
  //   let params = new FormData();
  //   params.append('fid', props.fid);

  //   let wattHourMeter = '';
  //   // $axios.post('/wattHourMeter/data', params).then(res => {
  //   //   wattHourMeter = res.data.data;
  //   //   /// proxy.$mitt.on('bigPieFn', (res) => {
  //   //   bigPie.value = bigPieFn.value;
  //   //   // bigPie.value=bigPie.value.filter((item)=>{
  //   //   //   return item.name=='官方展厅M'||item.name=='官方展厅H'||item.name=='官方展厅W3'
  //   //   // })
  //   //   echartsInitBigPie(myChart, bigPie.value, wattHourMeter)
  //   //   //  })

  // }).catch(err => { })

})
watch(
  () => props.fid,
  (newVal, oldVal) => {
    if (timer != null) {
      clearInterval(timer)
    }
    let params = new FormData();
    params.append('fid', props.fid == -1 ? 49 : props.fid);

    let wattHourMeter = '';
    $axios.post('/wattHourMeter/data', params).then(res => {
      wattHourMeter = res.data.data;
      /// proxy.$mitt.on('bigPieFn', (res) => {
      bigPie.value = bigPieFn.value;
      //   bigPie.value=bigPie.value.filter((item)=>{
      //     return item.name=='官方展厅M'||item.name=='官方展厅H'||item.name=='官方展厅W3'
      // })
      echartsInitBigPie(myChart, bigPie.value, wattHourMeter)
      // })

    }).catch(err => { })
    //   if (timer != null) {
    //   clearInterval(timer)
    // }
    // if (myChart[props.id] != null && myChart[props.id] != "" && myChart[props.id] != undefined) {
    //   myChart[props.id].dispose();//销毁
    // }
    // myChart[props.id] = echarts.init(document.getElementById(props.id));
    // myChart[props.id].setOption(LineBarChart())
  }
)
// const getErrDev = () => {
//     errDev.value = [];
//     $axios.post(`/operationDevice/getErrDev`, { "deviceFid": props.fid }).then(res => {
//         errDev.value = res.data.data;
//         //console.log("地址", res.data.data);
//     }).catch(err => { })
// }

const overhaul = () => {
  if (value2.value) {
    scrollM.value = true;
    console.log(props.fid);
    $axios.post("/homepage/lampStatusCheck", { "deviceFid": props.fid })
    timer = setInterval(function () {

    }, 1000);
  } else {
    scrollM.value = false;
    clearInterval(timer);
  }
  console.log("scrollM", scrollM.value);
  // errDev.value = props.errDev;
}
</script>
<style lang="scss" scoped>
.treeBox {
  width: 180px;
  border-right: solid 1px #fff;
  margin-right: 13px;
}

#chartRef {
  width: 100%;
  height: 320px;
}

.legendbox {
  width: 20%;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
  top: 35%;
  box-sizing: border-box;
  height: 65px;
}

.legendbox span {
  display: inline-block;
  margin-right: 4px;
  border-radius: 10px;
  width: 10px;
  height: 10px;
  margin-left: 15px;
}

.legendbox li {
  float: left;
  cursor: pointer;
  font-size: 12px;
  padding: 4px 0;
  height: 16px;
}

.device_status_normal {
  position: absolute;
  top: 41%;
  margin-right: 10px;
  margin-left: 15px;
  width: 19%;
}

.statusTop {
  justify-content: space-between;

}

.switch {
  margin-left: 30%;
}

.el-switch__label--left {
  color: #fff;
  /* 替换为你想要的颜色 */
}

.warnTextBox {
  height: 130px;
  overflow: hidden;
}
</style>